package com.spazioidro.application;

import java.util.ArrayList;
import java.util.List;

import com.spazioidro.adapters.ArticoloResultAdapter;
import com.spazioidro.json.JSONArray;
import com.spazioidro.json.JSONException;
import com.spazioidro.objects.Articolo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class SearchActivity extends Activity{
    JSONArray res=null;
    private ListView listResult;
    private List<Articolo> list_result;
    private Intent open_ar;
    private ProgressDialog pd;
    private Intent intent;
    private SharedPreferences prefs;
    private String username;
    private Context ctx;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_activity);
        ctx = this;
        //Recupero la listView dei risultati e creo l'adapter
        listResult = ( ListView ) findViewById( R.id.listViewSearchResult );
        listResult.setAdapter( new ArticoloResultAdapter( this, R.layout.article_list_search, new ArrayList<Articolo>() ) );
        //Recupero l'intent
        intent = getIntent();
        list_result = new ArrayList <Articolo>();  //Inizializzo la lista dei risultati
        Log.i("SearchActivity.onCreate()","Start activity");
        open_ar = new Intent (this,ArticleDetail.class);
        //Rendo cliccabile la listView e creo il listener
        listResult.setClickable(true);
        listResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressWarnings("unchecked")
          public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
              String cd_ar = ( ( ArrayAdapter<Articolo> ) listResult.getAdapter() ).getItem(position).getCd_ar();
              String pkg = getPackageName();
              open_ar.putExtra(pkg+".cd_ar", cd_ar);
              startActivity(open_ar);
          }
        });
        Log.i("SearchActivity","progressDialog creato");
        // Get the intent, verify the action and get the query
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
          String query = intent.getStringExtra(SearchManager.QUERY);
          Connection conn = new Connection();
          MyApplication application = (MyApplication) this.getApplication();
          prefs = getSharedPreferences(application.getLoginKey(), Context.MODE_PRIVATE);
          username = prefs.getString("username","cweb@cweb.it");
          conn.execute("search_by_key",query,username);          
        }
    }
    private class Connection extends AsyncTask <String,Articolo,Void> {
        @Override
        @SuppressWarnings("unchecked")
        protected void onPreExecute(){
            ( ( ArrayAdapter<Articolo> ) listResult.getAdapter() ).clear();
            String msg = getResources().getString(R.string.progress_loading);
            pd= ProgressDialog.show(SearchActivity.this,"Spazioidro",msg,true,false);
            super.onPreExecute();
            
        }
        @Override
        protected Void doInBackground(String...args) {
            Log.i("SearchActivity.doInBackground","inizia la connessione");
            try {
                ProxyUtils.init(ctx); 
                res = ProxyUtils.proxyCall_array(args[0], args[1], args[2]);
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            Log.i ("SearchActivity.doInBackground","Return: "+res.toString());
            if (res.length()!=0){ //se non ci sono articoli da mostrare non faccio nulla
                for (int i=0;i<res.length();i++){
                    try {   
                        String cd_ar = res.getJSONObject(i).getString("cd_ar");
                        String descrizione = res.getJSONObject(i).getString("descrizione");
                        String photo=null;
                        if (res.getJSONObject(i).has("photo"))
                            photo = res.getJSONObject(i).getString("photo");
                        String sconto = res.getJSONObject(i).getString("sconto");;
                        double prezzo = res.getJSONObject(i).getDouble("prezzo");
                        list_result.add(new Articolo(cd_ar,descrizione,photo,prezzo,sconto));
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }  
                }
            }   
            Log.i("SearchActivity.doInBackground","Operazione inviata: '"+args[0]+"', messaggio ricevuto: '"+res.toString()+"'");
            int list_length = list_result.size();
            Log.i ("doInBackground","size: "+list_length);
            for ( int i = 0; i < list_length; i++ ) {
                    // Pubblichiamo il progresso
                    Log.i ("doInBackground","Sto pubblicando il numero: "+i);
                    publishProgress(list_result.get(i)  );
            }
            return null;
        }
        @SuppressWarnings("unchecked")
        @Override
        protected void onProgressUpdate(Articolo... values) {
            ( ( ArrayAdapter<Articolo> ) listResult.getAdapter() ).add( values[0] );
            super.onProgressUpdate( values );
        }
        @Override
        protected void onPostExecute(Void res){
            super.onPostExecute(res);
            Log.i("onPostExecute","Rimuovo la progress bar");
            if(pd.isShowing())
                pd.dismiss();
        }
    }
}
